package com.example.demo.util;


import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


public class PackagingExcel {

    /**
     * zip4J工具类加密压缩方式
     *
     * @param toZipPath   压缩包地址
     * @param needZipPath 需要压缩的文件路径
     * @param password    密码
     * @return true 压缩成功 false 失败
     * @throws ZipException
     * @author lqy
     */
    public static boolean toZipFile(String toZipPath, String needZipPath, String password) throws ZipException {
        // 生成的压缩文件
        ZipFile zipFile = new ZipFile(toZipPath);
        ZipParameters parameters = new ZipParameters();
        // 压缩方式
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        // 压缩级别
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        if (!StringUtils.isEmpty(password)) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            parameters.setPassword(password);
        }
        // 要打包的文件夹
        File currentFile = new File(needZipPath);
        File[] fs = currentFile.listFiles();
        if (fs.length == 0) {
            zipFile.addFolder(currentFile.getPath(), parameters);
        }
        // 遍历test文件夹下所有的文件、文件夹
        for (File f : fs) {
            if (f.isDirectory()) {
                zipFile.addFolder(f.getPath(), parameters);
            } else {
                zipFile.addFile(f, parameters);
            }
        }

        return true;
    }

    public static void downloadFile(File file, HttpServletResponse response, boolean isDelete, HttpServletRequest request) throws Exception {
        try {
            // 以流的形式下载文件。
            BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));

            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();


            response.setContentType("multipart/form-data");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream;charset=utf-8");

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());


            String agent = request.getHeader("USER-AGENT"); //获取浏览器的信息
            if (agent != null && agent.toLowerCase().indexOf("firefox") > 0) {
                //火狐浏览器自己会对URL进行一次URL转码所以区别处理
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(file.getName().getBytes("GB2312"), "ISO-8859-1"));
            } else if (agent.toLowerCase().indexOf("safari") > 0) {
                //苹果浏览器需要用ISO 而且文件名得用UTF-8
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
            } else {
                //其他的浏览器
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
            }
//
//
//			response.setHeader("Content-Disposition",
//					"attachment;filename=" + new String(file.getName().getBytes("gb2312"), "ISO8859-1") + ".zip" + "\"");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            if (isDelete) {
                file.delete(); // 是否将生成的服务器端文件删除
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    /**
     * 文件名转化乱码修改
     *
     * @param fileName
     * @return
     * @throws
     * @throws UnsupportedEncodingException
     */
    public static String passCNcode(String fileName) throws UnsupportedEncodingException {
//		String remoteFileName = new String(fileName.getBytes("GBK"),System.getProperty("sun.jnu.encoding"));
        String remoteFileName = new String(fileName.getBytes("utf-8"));
        return remoteFileName;
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @throws IOException
     */
    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }


}
